package com.zFace.多线程轮流打印;

/**
 * 用 synchronized、wait、notify 实现 三个线程轮流打印十次
 */
public class Demo2 {

	private static int index = 1;

	public static void main(String[] args) throws InterruptedException {
		final Object lock = new Object();

		Runnable target;
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				synchronized (lock) {
					for (int i = 0; i < 10; i++) {
						while (index % 3 != 1) {
							try {
								lock.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
						System.out.println("a");
						index++;
						lock.notifyAll();
					}
				}
			}
		});
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				synchronized (lock) {
					for (int i = 0; i < 10; i++) {
						while (index % 3 != 2) {
							try {
								lock.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
						System.out.println("b");
						index++;
						lock.notifyAll();
					}
				}
			}
		});
		Thread t3 = new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (lock) {
					for (int i = 0; i < 10; i++) {
						while (index % 3 != 0) {
							try {
								lock.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
						System.out.println("c");
						index++;
						lock.notifyAll();
					}
				}
			}
		});

		t1.start();
		t2.start();
		t3.start();
		Thread.sleep(1000);
		System.out.println(index-1);
	}
}
